package cn.cellcom.agent.biz;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.pojo.TChannel;
import cn.cellcom.agent.pojo.TChannelRouter;
import cn.cellcom.agent.pojo.TGroup;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.TChannelForm;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.reflect.ToString;
import cn.cellcom.jar.util.CopyUtil;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.IDGenerator;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class TChannelBiz extends AbstractBiz {

	@Override
	public List delete(HttpServletRequest req, ActionForm form, Object obj) {

		return null;
	}

	@Override
	public Object add(HttpServletRequest req, ActionForm form, Object obj) {
		TChannelForm fm = (TChannelForm) form;
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		try {
			log.info("add log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String no = fm.getNo();
			// 你必须修改这里的id值
			if (no != null && this.getDao().myGet("from " + TChannel.class.getSimpleName() + " where no=? and pid=?",
					new String[] { no, user.getPid() }) != null) {
				return "该渠道号已经存在，不要重复添加";
			}
			TChannel pojo = new TChannel();
			// 以下为pojo的必填字段
			CopyUtil.copy(req, pojo, null, false);
			pojo.setId(IDGenerator.getDefaultUUID());
			pojo.setOrg(user.getOrg());
			pojo.setPid(user.getPid());
			pojo.setInsertTime(DT.getNow());

			this.getDao().mySave(pojo);

			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "新增数据出现错误", e);
		}
	}

	@Override
	public Object modify(HttpServletRequest req, ActionForm form, Object obj) {
		TChannelForm fm = (TChannelForm) form;
		LogonSession ls = new LogonSession(req);
		try {
			log.info("modify log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String key = fm.getId();
			TChannel pojo = (TChannel) this.getDao().myGet(TChannel.class, key);
			if (pojo == null) {
				return "修改的记录不存在";
			}
			log.info("被修改的pojo：" + ToString.toString(TChannel.class, pojo, false));

			CopyUtil.copy(req, pojo, null, false);
			this.getDao().myUpdate(pojo);

			this.getDao().myDelete("from " + TChannelRouter.class.getSimpleName() + " where channel = '" + pojo.getNo() + "'");
			String[] groups = req.getParameterValues("groups");
			for (int i = 0; groups != null && i < groups.length; i++) {
				TChannelRouter r = new TChannelRouter();
				r.setChannel(pojo.getNo());
				r.setCreateTime(System.currentTimeMillis());
				r.setId(IDGenerator.getDefaultUUID());
				r.setInSupportGroup(null);
				r.setOrg(pojo.getOrg());
				r.setPid(pojo.getPid());
				r.setRouteGroup(groups[i]);
				r.setStatus(AgentConstant.YES);
				this.getDao().mySave(r);
			}

			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "修改数据出现错误", e);
		}

	}

	/**
	 * 获取渠道信息
	 * 
	 * @param channelNo
	 * @param string
	 * @return
	 * @throws MyException
	 */
	public TChannel getChannelByNo(String org, String channelNo) throws MyException {
		String key = org + "-" + channelNo;
		if (cache.get(key) != null) {
			return cache.get(key);
		}
		TChannel ch = (TChannel) this.getDao().myGet("from " + TChannel.class.getSimpleName() + " where org=? and no=?",
				new String[] { org, channelNo });
		cache.put(key, ch);
		return ch;
	}

	private static Map<String, TChannel> cache = new HashMap<String, TChannel>();

	/**
	 * 通过微信的appid获取渠道
	 * 
	 * @param appid
	 * @return
	 * @throws MyException
	 */
	public TChannel getChannelByWcAppid(String appid) throws MyException {
		TChannel channel = cache.get(appid);
		if (channel == null) {
			channel = (TChannel) this.getDao().myGet("from " + TChannel.class.getSimpleName() + " where wcAppid=?", new String[] { appid });
			if (channel != null) {
				cache.put(appid, channel);
			}
		}
		return channel;
	}

	/**
	 * 通过QQ获取渠道
	 * 
	 * @param appid
	 * @return
	 * @throws MyException
	 */
	public TChannel getChannelByQq(String qq) throws MyException {
		TChannel channel = cache.get(qq);
		if (channel == null) {
			channel = (TChannel) this.getDao().myGet("from " + TChannel.class.getSimpleName() + " where qq=?", new String[] { qq });
			if (channel != null) {
				cache.put(qq, channel);
			}
		}
		return channel;
	}

	/**
	 * 获取某个渠道所配置的路由技能组
	 * 
	 * @param pid
	 * @param channel
	 * @return
	 * @throws MyException
	 */
	public List<TGroup> getRouteGroupsByNo(String pid, String channel) throws MyException {
		String hql = "select b from " + TChannelRouter.class.getSimpleName() + " as a, " + TGroup.class.getSimpleName()
				+ " as b where a.routeGroup=b.id and a.pid=? and a.channel=?";
		return this.getDao().myList(hql, new String[] { pid, channel });
	}

	/**
	 * 
	 * @param account
	 * @param channelNo
	 * @param channelMemo
	 * @throws MyException 
	 */
	public void createQqChannel(String org, String pid, String account, String channelNo, String channelMemo) throws MyException {
		TChannel pojo = new TChannel();
		pojo.setId(IDGenerator.getDefaultUUID());
		pojo.setOrg(org);
		pojo.setPid(pid);
		pojo.setName(channelNo);
		pojo.setMemo(channelMemo);
		pojo.setQq(account);
		pojo.setType(AgentConstant.CHANNEL_TYPE.QQ.name());
		pojo.setNo("Q" + account);
		pojo.setInsertTime(DT.getNow());
		this.getDao().mySave(pojo);
	}
}
